package com.ruoyi.project.nczxwechat.wechat.api;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.wx.WxMaConfiguration;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.nczxwechat.stuinfo.domain.WxStuinfo;
import com.ruoyi.project.nczxwechat.stuinfo.service.IWxStuinfoService;
import com.ruoyi.project.nczxwechat.wechat.domain.WxUserInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.Date;

/***
 * author：阿卜QQ932696181
 * 微信用户控制器
 */
@Controller
@RequestMapping("/wechat/api/user/")
public class ApiUserController {

    @Autowired
    IWxStuinfoService stuinfoService;

    /**
     * 先查询学生信息是否存在
     * @param stuno学生唯一ID
     */
    @GetMapping("getUserInfo")
    @ResponseBody
    public AjaxResult getUserInfo(@NotEmpty(message = "获取学生信息错误") String stuno){
            WxStuinfo wxStuinfo = stuinfoService.selectWxStuinfoByStuNo(stuno);
            if (wxStuinfo != null && StringUtils.isNotEmpty(wxStuinfo.getStuno())){
                return AjaxResult.success(wxStuinfo);
            }else {
                return AjaxResult.error("暂未查到绑定信息，请核对或与相关人员联系！");
            }
    }
    @ApiOperation(value = "获取微信openId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "微信code", required = true, dataType = "string"),
    })
    @PostMapping("wxlogin")
    @ResponseBody
    public AjaxResult wxlogin(@NotEmpty(message = "授权信息错误") @RequestBody WxUserInfo wxUserInfo)  {
        WxStuinfo wxStuinfos = stuinfoService.selectWxStuinfoByStuNo(wxUserInfo.getStuno());//通过学生唯一ID查询学生基本信息
        //通过微信端api获取当前用户的openid
        WxMaJscode2SessionResult session = null;
        try {
            session = WxMaConfiguration.wxMaService.getUserService().getSessionInfo(wxUserInfo.getCode());
            //通过当前用户的唯一编号与opendi查询学生信息
            WxStuinfo reswxStuinfo = stuinfoService.selectWxStuinfoByStuNoAndOpenID(wxUserInfo.getStuno(), wxStuinfos.getOpenId());
            //判断是否已绑定：就是旧的openid是否存在
            if (StringUtils.isEmpty(wxStuinfos.getOpenId())){
                //没有绑定就开始绑定，并返回相关数据
                updateUserInfo(session.getOpenid(),wxUserInfo);
                return AjaxResult.success(wxStuinfos);
                //存在并且已经绑定了判断是否跟原来绑定的一致
            }else if (StringUtils.isNotEmpty(reswxStuinfo.getOpenId())){
                //数据一致就返回库里的数据，成功登录并返回相关数据
                return AjaxResult.success(wxStuinfos);
            }else {
                //不一致就反馈错误信息
                return AjaxResult.error("你已经绑定过其他微信账号，请勿重复绑定！!");
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            return AjaxResult.error("本次授权失败，请与管理员联系");
        }
    }
    public String updateUserInfo(String openID, WxUserInfo wxuserinfo){
        Date date=new Date();
        WxStuinfo wxStuinfos = stuinfoService.selectWxStuinfoByStuNo(wxuserinfo.getStuno());
        wxStuinfos.setAvatarUrl(wxuserinfo.getAvatarUrl());
        wxStuinfos.setOpenId(openID);
        wxStuinfos.setNickName(wxuserinfo.getNickName());
        wxStuinfos.setFirstLoginTime(date);
        stuinfoService.updateWxStuinfo(wxStuinfos);
        return "绑定成功";
    }
}
